package thread.wang_bao_ling.c21;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.stream.IntStream;

/**
 * AtomicIntegerArray使用示例
 */
public class AtomicIntegerArrayTest {
    private static final int threadNum=5;
    static int[] array = new int[10];
    private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray (array);
    private static CountDownLatch  countDownLatch=new CountDownLatch(threadNum);

    public static void main(String[] args) throws InterruptedException {
        calculate();
        for (int i = 0; i < array.length; i++) {
            //注意原数组array中的值是不会变的，因为在构造AtomicIntegerArray时是将原数组clone了一份
            System.out.println(atomicIntegerArray.get(i));
        }
    }


    /**
     * 创建多个线程进行累加
     * @throws InterruptedException
     */
    public static long calculate() throws InterruptedException {
        long start=System.currentTimeMillis();
        IntStream.range(0, 5).forEach(f->{
            new Thread(()->{
                add1w();
                try {
                    countDownLatch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        });
        countDownLatch.await();
        return System.currentTimeMillis()-start;
    }


    /**
     * 每个数组元素加1w
     */
    private static void add1w() {
        int idx = 0;
        while(idx++ < 10000) {
            for (int i = 0; i < array.length; i++) {
                atomicIntegerArray.getAndIncrement(i);
            }
        }
    }

}
